package com.yanqu.road.dao.impl.curio;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.curio.CurioItemMaxScore;
import com.yanqu.road.entity.curio.CurioPrivilege;
import com.yanqu.road.entity.curio.UserCurioItemData;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserCurioItemDataDaoImpl extends TempDataObjectDao<UserCurioItemData> {

    public Map<Integer, CurioItemMaxScore> getMaxScoreMap(){
        String sql = "SELECT t.userId,t.itemId,t.score,t.scoreUpdateTime from t_u_curio_item t INNER JOIN ( select itemId,max(score) as maxScore from t_u_curio_item GROUP BY itemId) i on t.itemId = i.itemId and i.maxScore = t.score";
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, CurioItemMaxScore> map = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                long score = rs.getLong("score");
                long userId = rs.getLong("userId");
                long scoreUpdateTime = rs.getLong("scoreUpdateTime");
                int itemId = rs.getInt("itemId");
                CurioItemMaxScore data = map.get(itemId);
                if(data == null){
                    data = new CurioItemMaxScore(itemId, score, userId, scoreUpdateTime);
                    map.put(itemId, data);
                }else {
                    if(scoreUpdateTime < data.getLastUpdateTime()){
                        data.setLastUpdateTime(scoreUpdateTime);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);} finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }

    public static String getUserCurioItemDataSql = "select * from `t_u_curio_item` where `userId`=?";
    public Map<Integer, UserCurioItemData> getUserCurioItemData(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, UserCurioItemData> map = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(getUserCurioItemDataSql);
            int i = 1;
            call.setLong(i++, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserCurioItemData data = parse(rs);
                map.put(data.getItemId(), data);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);} finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }

    public static String updateUserCurioItemDataSql = "update `t_u_curio_item` set quality=?,lv=?,starLv=?,score=?,scoreUpdateTime=?,privilegeList=? where userId=? and itemId=?";
    @Override
    protected boolean updateData(UserCurioItemData userCurioItemData) {
        userCurioItemData.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getQuality()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getLv()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getStarLv()));
        para.put(i++, new DbParameter(Types.BIGINT, userCurioItemData.getScore()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getScoreUpdateTime()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(userCurioItemData.getPrivilegeList())));
        para.put(i++, new DbParameter(Types.BIGINT, userCurioItemData.getUserId()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getItemId()));
        if (getDb().executeNoneQuery(updateUserCurioItemDataSql, para) > 0) {
            return true;
        }
        return false;
    }

    public static String insertUserCurioItemDataSql = "insert into `t_u_curio_item`(userId,itemId,quality,lv,starLv,score,scoreUpdateTime,privilegeList) values (?,?,?,?,?,?,?,?)";
    @Override
    protected boolean addData(UserCurioItemData userCurioItemData) {
        userCurioItemData.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, userCurioItemData.getUserId()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getItemId()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getQuality()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getLv()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getStarLv()));
        para.put(i++, new DbParameter(Types.BIGINT, userCurioItemData.getScore()));
        para.put(i++, new DbParameter(Types.INTEGER, userCurioItemData.getScoreUpdateTime()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(userCurioItemData.getPrivilegeList())));
        if (getDb().executeNoneQuery(insertUserCurioItemDataSql, para) > 0) {
            return true;
        }
        return false;

    }

    @Override
    protected UserCurioItemData parseData(ResultSet rs) throws SQLException {
        UserCurioItemData userCurioItemData = new UserCurioItemData();
        userCurioItemData.setUserId(rs.getLong("userId"));
        userCurioItemData.setItemId(rs.getInt("itemId"));
        userCurioItemData.setQuality(rs.getInt("quality"));
        userCurioItemData.setLv(rs.getInt("lv"));
        userCurioItemData.setStarLv(rs.getInt("starLv"));
        userCurioItemData.setScore(rs.getLong("score"));
        userCurioItemData.setScoreUpdateTime(rs.getInt("scoreUpdateTime"));
        String privilege = rs.getString("privilegeList");
        if(StringUtils.isNullOrEmpty(privilege)){
            userCurioItemData.setPrivilegeList(new ArrayList<>());
        }else {
            userCurioItemData.setPrivilegeList(JSON.parseObject(privilege, new TypeReference<List<CurioPrivilege>>() {}));
        }
        return userCurioItemData;
    }
}
